import Vue from "vue";
import Vuex from "vuex";
import api from '../api/request.js'
Vue.use(Vuex);

const store = new Vuex.Store({
	state: {
		token: uni.getStorageSync('AppToken') || '',
		userInfo: uni.getStorageSync('userInfo') || {},
		productCategoryList: [],
		cartData: [],
		cartNumber: 0,
		chinaData: {
			data: [],
			province: [],
			city: [],
			area: [],
			hongkong: [],
			aomen: []
		}
	},
	mutations: {
		setToken(state, token) {
			state.token = token;
			uni.setStorageSync('AppToken', token)
			console.log(uni.getStorageSync('AppToken'))
		},
		async setUserInfo(state) {
			const userInfo = await api.get('/getInfo', {}, false)
			if (userInfo.code !== 200) return
			const supplyWarehouseInfo = await api.get('/adm/supplywarehouse/getInfo', {
				id: userInfo.user.supplyWarehouseId
			}, false)
			userInfo.user.supplyWarehouseInfo = supplyWarehouseInfo.data;
			uni.setStorageSync('userInfo', userInfo.user)
			state.userInfo = userInfo.user;
			console.log('userInfo.data', userInfo.user)
		},
		setProductCategoryList(state, list) {
			state.productCategoryList = JSON.parse(JSON.stringify(list));
			//uni.setStorageSync('productCategoryList', state.productCategoryList)
		},
		setChinaData(state, data) {
			state.chinaData[data.name] = data.data;
		},
		setCartList(state) {
			state.cartData = uni.getStorageSync('cartData') || [];
			state.cartNumber = state.cartData.length;
			uni.setStorageSync('cartNumber', state.cartNumber)
		},
		addCartList(state, obj) {
			const productIndex = state.cartData.findIndex(item => item.productId === obj.productId)
			if (productIndex > -1) { // 如果当前购物车有该商品
				let selected = state.cartData[productIndex].selected;
				obj.selected = selected;
				state.cartData[productIndex] = obj;
			} else {
				obj.selected = true;
				state.cartData.push(obj)
			}
			uni.getStorageSync('cartData', state.cartData)
			state.cartNumber = state.cartData.length;
			uni.setStorageSync('cartNumber', state.cartNumber)
		},
		selectCartList(state, obj) {
			state.cartData.forEach(item => {
				if (item.productId === obj.productId) {
					item.selected = obj.selected || false;
				}
			})
			uni.getStorageSync('cartData', state.cartData)
		},
		removeCartList(state, obj) {
			let index = state.cartData.findIndex(item => item.productId === obj.productId)
			if (index > -1) {
				state.cartData.splice(index, 1)
				uni.getStorageSync('cartData', state.cartData)
				state.cartNumber = state.cartData.length;
				uni.setStorageSync('cartNumber', state.cartNumber)
			}
		},
	}
})

export default store